package com.example.djs;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity2 extends AppCompatActivity {

    private EditText editText, editText2;
    private CheckBox checkBox;
    private Boolean rememberUser = false;
    private SharedPreferences sharedPreferences;

    private final String UserSharedPreferencesStoreName = "User";
    private final String UserSharedPreferencesName = "name";
    private final String UserSharedPreferencesPassword = "password";
    private final String UserSharedPreferencesRememberUser = "rememberUser";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        editText = findViewById(R.id.editText);
        editText2 = findViewById(R.id.editText2);
        checkBox = findViewById(R.id.checkBox);
        sharedPreferences = getSharedPreferences(UserSharedPreferencesStoreName, MODE_PRIVATE);

        rememberUser = sharedPreferences.getBoolean(UserSharedPreferencesRememberUser, false);
        checkBox.setChecked(rememberUser);
        if (rememberUser) {
            String userName = sharedPreferences.getString(UserSharedPreferencesName, "");
            String password = sharedPreferences.getString(UserSharedPreferencesPassword, "");
            editText.setText(userName);
            editText2.setText(password);
        }

        Button loginButton = findViewById(R.id.textView2);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                String password = editText2.getText().toString();
                if (name.isEmpty() || password.isEmpty()) {
                    Toast.makeText(MainActivity2.this, "用户名或密码为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString(UserSharedPreferencesName, name)
                        .putString(UserSharedPreferencesPassword, password)
                        .putBoolean(UserSharedPreferencesRememberUser, checkBox.isChecked())
                        .apply();

                Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
                startActivity(intent);
                finish();
            }
        });
    }
}